package net.ys.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.ys.utils.req.HttpClient;
import net.ys.utils.req.HttpResponse;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: NMY
 * @Date: 2021/6/23
 * @Time: 8:24
 */
public class Tools {

    static final int HTTP_OK = 200;
    static final String HTTP_OK_MSG = "OK";
    static SimpleDateFormat yMdHms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 钉钉通知
     */
    public static boolean ddNotice(String url, JSONObject msg) {
        JSONObject at = new JSONObject();
        JSONArray atMobiles = new JSONArray();
        atMobiles.add("all");
        at.put("atMobiles", atMobiles);
        at.put("isAtAll", true);
        msg.put("at", at);

        HttpResponse response = HttpClient.doPostJson(url, msg.toJSONString());
        if (response.getCode() == HTTP_OK) {
            String value = response.getValue();
            if (value.contains(HTTP_OK_MSG)) {
                return true;
            }
        }
        return false;
    }

    public static String ddSign(long timestamp, String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
    }

    /**
     * 微信通知
     *
     * @return
     */
    public static boolean wxNotice(String url, String content) {
        JSONObject msg = new JSONObject();
        msg.put("msgtype", "markdown");
        JSONObject markdown = new JSONObject();
        markdown.put("content", content);
        JSONArray mentionedList = new JSONArray();
        mentionedList.add("@all");
        markdown.put("mentioned_list", mentionedList);
        msg.put("markdown", markdown);

        HttpResponse response = HttpClient.doPostJson(url, msg.toJSONString());
        if (response.getCode() == HTTP_OK) {
            String value = response.getValue();
            if (value.contains(HTTP_OK_MSG)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 转化时间
     *
     * @param time
     * @return
     */
    public static String toYmdHms(long time) {
        if (time == 0) {
            return "";
        }
        Date date = new Date();
        date.setTime(time);
        return yMdHms.format(date);
    }
}
